import uuid

from drf_haystack.viewsets import HaystackViewSet

from rest_framework import mixins, viewsets
from rest_framework.decorators import authentication_classes
from rest_framework.pagination import CursorPagination
from rest_framework.response import Response
from rest_framework.throttling import UserRateThrottle, AnonRateThrottle

from goods.filters import GoodsFilter
from goods.models import Goods, GoodsCategory, GoodsImage
from goods.serializers import GoodsIndexSerialiser, GoodsNavSerialiser, GoodsCreateSerializers, \
    GoodsListSerializers, GoodsDetailSerializers
from user.authentications import JsonWebTokenAuthentication


class GoodsPagination(CursorPagination):
    #页面大小
    page_size = 30
    #查询参数
    cursor_query_param = 'cursor'
    #最多查询页数
    max_page_size = 20


class GoodsListViewSet(mixins.ListModelMixin,mixins.CreateModelMixin,mixins.RetrieveModelMixin,viewsets.GenericViewSet):
    """
    list:
        商品列表，分页
    retrieve:
        获取商品详情
    """
    throttle_classes = (UserRateThrottle,AnonRateThrottle)
    queryset = Goods.objects.all().order_by('-add_time')
    #pagination_class = GoodsPagination
    serializer_class = GoodsListSerializers
    # filter_class = GoodsFilter

    def create(self, request, *args, **kwargs):
        print(request)
        print(*args)
        print(**kwargs)
        #serializer = self.get_serializer(data=request.data)
        # try:
        # #run_validation->self.to_internal_value->field.get_value会将值作为html_dict解析，会匹配regex
        #     serializer.is_valid(raise_exception=True)
        # except Exception as e:
        #     print(e)
        print(request.user)
        good = Goods.objects.create(goods_sn=uuid.uuid4(),
                                    goods_price=request.data['goods_price'],
                                    goods_brief=request.data['goods_brief'],
                                    seller_id=request.data['sellername'],
                                    category_id='1',
                                    )
        imglist = []
        imggroup = request.FILES.getlist('images')
        for img in imggroup:
            imglist.append(GoodsImage(image=img,good=good))
        goodimages = GoodsImage.objects.bulk_create(imglist)
        good.images_set = goodimages
        good.goods_front_image = imggroup[0]
        good.save()
        return Response('发布成功')

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.click_num += 1
        instance.save()
        serializer = self.get_serializer(instance)
        return Response(serializer.data)

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return GoodsDetailSerializers
        elif self.action == 'create':
            return GoodsCreateSerializers
        elif self.action == 'list':
            return GoodsListSerializers

    # def get_authenticators(self):
    #     if self.request.method == 'POST':
    #         return [JsonWebTokenAuthentication(),]


class GoodsSearchViewSet(HaystackViewSet):
    """
    商品搜索类
    """
    index_models = [Goods]
    #queryset = Goods.objects.all()
    pagination_class = GoodsPagination
    serializer_class = GoodsIndexSerialiser


class GoodsNavViewSet(mixins.ListModelMixin,viewsets.GenericViewSet):
    queryset = GoodsCategory.objects.filter(category_type=1)
    serializer_class = GoodsNavSerialiser



